<!--vue模板-->
<template>
  <el-dialog
    @close="close"
    v-model="visible"
    :close-on-click-modal="false"
    :title="ruleForm.id ? '更新产品' : '添加产品'"
    width="60%"
    draggable
  >
    <!-- 表单数据 -->
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="ruleForm"
      status-icon
    >
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="ruleForm.name"
          class="ipt"
          placeholder="请输入产品名称"
        />
      </el-form-item>

      <!-- 选择树 -->
      <el-form-item label="产品类别" prop="categoryName">
        <el-tree-select
          v-model="ruleForm.categoryName"
          @node-click="handleNodeClick" 
          :data="treeData"
          check-strictly
          :render-after-expand="false"
          :props="defaultProps"
        />
      </el-form-item>

      <el-form-item label="产品单位" prop="unit">
        <el-input
          v-model="ruleForm.unit"
          class="ipt"
          placeholder="请输入产品单位"
        />
      </el-form-item>

      <el-form-item label="规格型号" prop="spec">
        <el-input
          v-model="ruleForm.spec"
          class="ipt"
          placeholder="请输入规格型号"
        />
      </el-form-item>

      <el-form-item label="单价" prop="price">
        <el-input
          v-model="ruleForm.price"
          class="ipt"
          placeholder="请输入产品单价"
        />
      </el-form-item>

      <el-form-item label="说明" prop="note">
        <el-input
          v-model="ruleForm.note"
          class="ipt"
          placeholder="请输入产品说明"
        />
      </el-form-item>

      <el-form-item label="产品照片" prop="picurl">
        <el-upload class="avatar-uploader" :action="uploadUrl"
          :show-file-list=" false " :on-success=" handleAvatarSuccess " :before-upload=" beforeAvatarUpload ">
          <img v-if=" imageUrl " :src=" imageUrl " class="avatar" style="width: 300px;" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<!--vue 组件选项定义-->
<script setup>
import { inject, onBeforeMount, reactive, ref } from "vue";

import { ElMessage,ElMessageBox } from "element-plus";

import { saveProduct ,updateProduct } from '@/api/basic/Product.js'

import host from "@/util/DEV_ADDRESS";
import { queryCategoryAll,  queryById } from "@/api/basic/Category.js";

import { getUserInfo } from '@/util/auth.js'


const tmp = ref()

// 定义文件的上传路径
const uploadUrl = ref(host + 'upload')

const ruleFormRef = ref(null);
// 控制添加更新的显示隐藏
const visible = inject("isShow");
const pidAdd = inject("pidAdd");
// 定义树节点
const treeData = ref({})

async function initTree() {
  const res = await queryCategoryAll();
  treeData.value = res.data;
  
}

const defaultProps = {
  children: "children",
  label: "name",
  value: "name",
  id: "id",
};

onBeforeMount(() => {
  initTree()
})


const handleNodeClick = (data) => {
  ruleForm.value.categoryName = data.name
  ruleForm.value.categoryCode = data.code
}



// 图片上传
const imageUrl = ref('')

const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  ruleForm.value.picurl = response.data
  console.log(response,"图片上传");
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 10MB!')
    return false
  }
  return true
}

// 表单
const ruleForm = ref({
  id: "",
  name: "",
  code: "",
  categoryName: "",
  categoryCode: "",
  unit: "",
  spec: "",
  price: "",
  note: "",
  picurl: "",
  adduserId: ""
});

function init(data){
  ruleForm.value = data
  imageUrl.value = data.picurl
}
// 初始化表单数据
defineExpose({ init })

// 校验
const rules = {
  name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
};
const emit = defineEmits(["close"]);

function close() {
  delete ruleForm.value.id;
    // 重置表单 去除之前的校验
  console.log(ruleFormRef,"ruleForm");
  ruleFormRef.value.resetFields();
  visible.value = false;
  imageUrl.value = ""

  emit("close");
}

// 暴露接口

// 保存用户信息
const saveCategory = () => {
  ruleFormRef.value.validate((val) => {
    console.log(val, "val");
    if (val) {
      ruleForm.value.adduserId = getUserInfo().id
      // 更新用户
      if (ruleForm.value.id) {
        console.log("更新尚品");
        console.log(ruleForm.value);
        updateProduct(ruleForm.value).then(resp => {
          ElMessage.success("更新成功！")
          close()
        })
      } else {
        console.log("添加尚品");
        console.log(ruleForm.value);
        saveProduct(ruleForm.value).then(resp => {
          ElMessage.success("添加成功！")
          close()
        })

        
      }
    }
  });
};
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.ipt {
  width: 90%;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
